<template>
  <div class="diet-record-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="饮食记录"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <!-- 日期选择器 -->
    <div class="date-selector">
      <van-cell
        title="日期"
        :value="formatDate(selectedDate)"
        @click="showDatePicker = true"
      />
      <van-calendar
        v-model="showDatePicker"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onDateSelected"
      />
    </div>

    <!-- 饮食记录列表 -->
    <div class="diet-records-list">
      <!-- 如果有记录，显示记录列表 -->
      <template v-if="dietRecords.length > 0">
        <div v-for="record in dietRecords" :key="record.id" class="record-item">
          <div class="record-header">
            <div class="meal-type" :class="getMealTypeClass(record.meal_type)">
              {{ record.meal_type }}
            </div>
            <div class="record-time">{{ formatTime(record.eat_time) }}</div>
            <van-icon
              name="delete-o"
              class="delete-icon"
              @click="confirmDeleteRecord(record.id)"
            />
          </div>
          <div
            class="record-content"
            @click="goToRecipeDetail(record.recipe_id)"
          >
            <div class="recipe-image">
              <van-image
                width="70"
                height="70"
                :src="record.recipe_image || defaultImage"
                fit="cover"
                radius="4"
              />
            </div>
            <div class="recipe-info">
              <div class="recipe-name">{{ record.recipe_name }}</div>
              <div class="calories">{{ record.calories }} 卡路里</div>
              <div class="portion">{{ record.portion }}份</div>
            </div>
          </div>
          <div class="record-footer">
            <div class="satisfaction">
              满意度:
              <van-rate v-model="record.satisfaction" readonly :count="5" />
            </div>
          </div>
        </div>
      </template>

      <!-- 如果无记录，显示空状态 -->
      <div class="empty-state" v-if="dietRecords.length === 0 && !loading">
        <van-empty description="暂无饮食记录" />
        <p class="empty-tip">点击下方按钮添加今日饮食记录</p>
      </div>

      <!-- 加载状态 -->
      <div class="loading-state" v-if="loading">
        <van-loading color="#1989fa" />
        <p>加载中...</p>
      </div>
    </div>

    <!-- 今日营养摘要 -->
    <div class="nutrition-summary" v-if="dietRecords.length > 0">
      <div class="summary-header">今日营养摘要</div>
      <div class="summary-grid">
        <div class="summary-item">
          <div class="item-value">
            {{ dailySummary.totalCalories }} <span class="unit">kcal</span>
          </div>
          <div class="item-label">总热量</div>
          <div class="item-progress">
            <van-progress
              :percentage="caloriesPercentage"
              :show-pivot="false"
              stroke-width="5"
            />
            <div class="progress-text">{{ caloriesPercentage }}%</div>
          </div>
        </div>
        <div class="summary-item">
          <div class="item-value">
            {{ dailySummary.totalProtein }} <span class="unit">g</span>
          </div>
          <div class="item-label">蛋白质</div>
        </div>
        <div class="summary-item">
          <div class="item-value">
            {{ dailySummary.totalFat }} <span class="unit">g</span>
          </div>
          <div class="item-label">脂肪</div>
        </div>
        <div class="summary-item">
          <div class="item-value">
            {{ dailySummary.totalCarbs }} <span class="unit">g</span>
          </div>
          <div class="item-label">碳水</div>
        </div>
      </div>
    </div>

    <!-- 添加按钮 -->
    <div class="add-button">
      <van-button
        type="primary"
        round
        icon="plus"
        size="normal"
        @click="showAddForm = true"
      >
        添加饮食记录
      </van-button>
    </div>

    <!-- 添加饮食记录表单 -->
    <van-popup
      v-model="showAddForm"
      position="bottom"
      :style="{ height: '80%' }"
    >
      <div class="add-record-popup">
        <div class="popup-header">
          <div class="popup-title">添加饮食记录</div>
          <van-icon name="cross" @click="showAddForm = false" />
        </div>

        <van-form @submit="handleAddRecord">
          <van-cell-group inset>
            <van-field
              readonly
              label="餐食类型"
              placeholder="请选择餐食类型"
              :modelValue="addForm.meal_type"
              @click="showMealTypePicker = true"
            />

            <van-field
              readonly
              label="食谱"
              placeholder="请选择食谱"
              :modelValue="addForm.recipe_name"
              @click="goToRecipeSearch"
            />

            <van-field
              v-model="addForm.portion"
              type="digit"
              label="份量"
              placeholder="请输入份量"
            />

            <van-field
              v-model="addForm.calories"
              type="digit"
              label="热量(kcal)"
              placeholder="根据食谱自动计算"
              readonly
            />

            <van-field name="satisfaction" label="满意度">
              <template #input>
                <van-rate v-model="addForm.satisfaction" :count="5" />
              </template>
            </van-field>
          </van-cell-group>

          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit">
              保存记录
            </van-button>
          </div>
        </van-form>

        <!-- 餐食类型选择器 -->
        <van-popup v-model="showMealTypePicker" position="bottom">
          <van-picker
            :columns="mealTypeOptions"
            @confirm="onMealTypeConfirm"
            @cancel="showMealTypePicker = false"
            show-toolbar
            title="选择餐食类型"
          />
        </van-popup>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { showToast, showSuccessToast, showConfirmDialog } from "vant";
import dayjs from "dayjs";
import { useUserStore } from "../../stores/userStore";
import {
  getUserDietRecords,
  addUserDietRecord,
  getUserHealth,
} from "../../api/user";

const router = useRouter();
const userStore = useUserStore();
const userId = computed(() => userStore.userId);

// 默认食谱图片
const defaultImage = "https://img.yzcdn.cn/vant/apple-1.jpg";

// 日期选择相关
const selectedDate = ref(new Date());
const showDatePicker = ref(false);
const minDate = new Date(new Date().getFullYear() - 1, 0, 1);
const maxDate = new Date();

// 饮食记录列表
const dietRecords = ref([]);
const loading = ref(false);

// 添加表单相关
const showAddForm = ref(false);
const showMealTypePicker = ref(false);
const mealTypeOptions = ["早餐", "午餐", "晚餐", "加餐"];
const addForm = reactive({
  meal_type: "",
  recipe_id: "",
  recipe_name: "",
  recipe_image: "",
  portion: 1,
  calories: 0,
  satisfaction: 3,
});

// 每日营养摘要
const dailySummary = reactive({
  totalCalories: 0,
  totalProtein: 0,
  totalFat: 0,
  totalCarbs: 0,
});

// 用户健康信息
const userHealth = ref(null);

// 计算热量百分比
const caloriesPercentage = computed(() => {
  if (
    !userHealth.value ||
    !userHealth.value.calorie_needs ||
    userHealth.value.calorie_needs === 0
  ) {
    return 0;
  }

  const percentage = Math.round(
    (dailySummary.totalCalories / userHealth.value.calorie_needs) * 100
  );
  return Math.min(percentage, 100); // 不超过100%
});

// 日期格式化
const formatDate = (date) => {
  return dayjs(date).format("YYYY-MM-DD");
};

// 时间格式化
const formatTime = (time) => {
  return dayjs(time).format("HH:mm");
};

// 获取餐食类型样式
const getMealTypeClass = (mealType) => {
  switch (mealType) {
    case "早餐":
      return "meal-breakfast";
    case "午餐":
      return "meal-lunch";
    case "晚餐":
      return "meal-dinner";
    case "加餐":
      return "meal-snack";
    default:
      return "";
  }
};

// 日期选择回调
const onDateSelected = (date) => {
  selectedDate.value = date;
  loadDietRecords();
  showDatePicker.value = false;
};

// 餐食类型选择回调
const onMealTypeConfirm = (value) => {
  addForm.meal_type = value;
  showMealTypePicker.value = false;
};

// 跳转到食谱搜索页面
const goToRecipeSearch = () => {
  // 保存当前状态，以便在食谱选择后返回
  localStorage.setItem(
    "addDietRecord",
    JSON.stringify({
      meal_type: addForm.meal_type,
      portion: addForm.portion,
      satisfaction: addForm.satisfaction,
    })
  );

  router.push("/recipe/search?fromDietRecord=true");
};

// 跳转到食谱详情页
const goToRecipeDetail = (recipeId) => {
  router.push(`/recipe/${recipeId}`);
};

// 加载饮食记录
const loadDietRecords = async () => {
  try {
    loading.value = true;
    const formattedDate = formatDate(selectedDate.value);

    const res = await getUserDietRecords(userId.value, { date: formattedDate });
    if (res.code === 200 && res.data) {
      dietRecords.value = res.data.records || [];

      // 计算每日摘要
      calculateDailySummary();
    } else {
      dietRecords.value = [];
      resetDailySummary();
    }
  } catch (error) {
    console.error("加载饮食记录失败", error);
    showToast("加载饮食记录失败");
    dietRecords.value = [];
    resetDailySummary();
  } finally {
    loading.value = false;
  }
};

// 加载用户健康信息
const loadUserHealth = async () => {
  try {
    const res = await getUserHealth(userId.value);
    if (res.code === 200 && res.data) {
      userHealth.value = res.data;
    }
  } catch (error) {
    console.error("加载用户健康信息失败", error);
  }
};

// 计算每日营养摘要
const calculateDailySummary = () => {
  dailySummary.totalCalories = 0;
  dailySummary.totalProtein = 0;
  dailySummary.totalFat = 0;
  dailySummary.totalCarbs = 0;

  dietRecords.value.forEach((record) => {
    dailySummary.totalCalories += Number(record.calories || 0);
    dailySummary.totalProtein += Number(record.protein || 0);
    dailySummary.totalFat += Number(record.fat || 0);
    dailySummary.totalCarbs += Number(record.carbs || 0);
  });

  // 转换为固定小数位
  dailySummary.totalCalories = dailySummary.totalCalories.toFixed(0);
  dailySummary.totalProtein = dailySummary.totalProtein.toFixed(1);
  dailySummary.totalFat = dailySummary.totalFat.toFixed(1);
  dailySummary.totalCarbs = dailySummary.totalCarbs.toFixed(1);
};

// 重置每日摘要
const resetDailySummary = () => {
  dailySummary.totalCalories = 0;
  dailySummary.totalProtein = 0;
  dailySummary.totalFat = 0;
  dailySummary.totalCarbs = 0;
};

// 添加饮食记录
const handleAddRecord = async () => {
  try {
    if (!addForm.meal_type) {
      return showToast("请选择餐食类型");
    }

    if (!addForm.recipe_id) {
      return showToast("请选择食谱");
    }

    const data = {
      userId: userId.value,
      recipeId: addForm.recipe_id,
      mealType: addForm.meal_type,
      portion: addForm.portion,
      calories: addForm.calories,
      satisfaction: addForm.satisfaction,
      eatTime: dayjs(selectedDate.value).format("YYYY-MM-DD HH:mm:ss"),
    };

    const res = await addUserDietRecord(data);
    if (res.code === 200) {
      showSuccessToast("添加饮食记录成功");
      showAddForm.value = false;
      resetAddForm();
      loadDietRecords();
    } else {
      showToast(res.message || "添加失败");
    }
  } catch (error) {
    console.error("添加饮食记录失败", error);
    showToast("添加失败，请稍后重试");
  }
};

// 确认删除记录
const confirmDeleteRecord = (id) => {
  showConfirmDialog({
    title: "删除确认",
    message: "确定要删除这条饮食记录吗？",
  }).then(() => {
    deleteRecord(id);
  });
};

// 删除饮食记录
const deleteRecord = async (id) => {
  try {
    const res = await deleteUserDietRecord(id, userId.value);
    if (res.code === 200) {
      showSuccessToast("删除成功");
      loadDietRecords();
    } else {
      showToast(res.message || "删除失败");
    }
  } catch (error) {
    console.error("删除饮食记录失败", error);
    showToast("删除失败，请稍后重试");
  }
};

// 重置添加表单
const resetAddForm = () => {
  addForm.meal_type = "";
  addForm.recipe_id = "";
  addForm.recipe_name = "";
  addForm.recipe_image = "";
  addForm.portion = 1;
  addForm.calories = 0;
  addForm.satisfaction = 3;
};

// 初始化
onMounted(async () => {
  await Promise.all([loadDietRecords(), loadUserHealth()]);

  // 检查是否从食谱选择页面返回
  const selectedRecipe = JSON.parse(
    localStorage.getItem("selectedRecipe") || "null"
  );
  const savedForm = JSON.parse(localStorage.getItem("addDietRecord") || "null");

  if (selectedRecipe && savedForm) {
    addForm.recipe_id = selectedRecipe.id;
    addForm.recipe_name = selectedRecipe.name;
    addForm.recipe_image = selectedRecipe.image;
    addForm.meal_type = savedForm.meal_type || "";
    addForm.portion = savedForm.portion || 1;
    addForm.satisfaction = savedForm.satisfaction || 3;

    // 根据食谱和份量计算卡路里
    if (selectedRecipe.calories) {
      addForm.calories = Math.round(selectedRecipe.calories * addForm.portion);
    }

    // 清除本地存储
    localStorage.removeItem("selectedRecipe");
    localStorage.removeItem("addDietRecord");

    // 自动打开添加表单
    showAddForm.value = true;
  }
});
</script>

<style scoped>
.diet-record-container {
  padding-top: 46px;
  padding-bottom: 80px;
}

.date-selector {
  margin: 10px 0;
}

.diet-records-list {
  margin: 10px 0;
}

.record-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.record-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.meal-type {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  margin-right: 10px;
}

.meal-breakfast {
  background-color: #e8f4ff;
  color: #1989fa;
}

.meal-lunch {
  background-color: #fef0e5;
  color: #ff976a;
}

.meal-dinner {
  background-color: #f0f9eb;
  color: #07c160;
}

.meal-snack {
  background-color: #f5f5f5;
  color: #646566;
}

.record-time {
  flex: 1;
  font-size: 12px;
  color: #969799;
}

.delete-icon {
  color: #ee0a24;
}

.record-content {
  display: flex;
  margin-bottom: 10px;
}

.recipe-image {
  margin-right: 12px;
}

.recipe-info {
  flex: 1;
}

.recipe-name {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 5px;
}

.calories {
  font-size: 12px;
  color: #ff976a;
  margin-bottom: 3px;
}

.portion {
  font-size: 12px;
  color: #969799;
}

.record-footer {
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f5f5f5;
  padding-top: 8px;
}

.satisfaction {
  font-size: 12px;
  color: #969799;
  display: flex;
  align-items: center;
}

.empty-state,
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.empty-tip {
  margin-top: 10px;
  color: #999;
  font-size: 13px;
}

.nutrition-summary {
  background-color: #fff;
  border-radius: 8px;
  padding: 12px;
  margin: 10px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.summary-header {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 12px;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.summary-item {
  padding: 8px;
  background-color: #f7f8fa;
  border-radius: 6px;
}

.item-value {
  font-size: 16px;
  font-weight: bold;
  color: #1989fa;
}

.unit {
  font-size: 12px;
  color: #999;
}

.item-label {
  font-size: 12px;
  color: #666;
  margin: 4px 0;
}

.item-progress {
  margin-top: 5px;
  position: relative;
}

.progress-text {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  text-align: center;
  font-size: 10px;
  color: #666;
}

.add-button {
  position: fixed;
  bottom: 20px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
}

.add-record-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.popup-title {
  font-size: 18px;
  font-weight: bold;
}
</style>
